import React, { useState, useEffect } from "react";
import {
  Flag,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Search,
  Filter,
  Eye,
  User,
  Calendar,
  Edit,
} from "lucide-react";
import { api } from "../../services/backendApi";
import { authService } from "../../services/authService";
import QuizEditModal from "../../components/QuizEditModal";
import { useToast, ToastContainer } from "../../components/Toast";

interface QuizReport {
  id: string;
  quiz_id: string;
  user_id: string;
  user_name?: string;
  report_type:
    | "display_error"
    | "wrong_answer"
    | "wrong_association"
    | "duplicate"
    | "unclear_wording"
    | "other";
  reason?: string;
  user_answer?: string;
  status: "pending" | "reviewing" | "resolved" | "dismissed";
  created_at: string;
  updated_at: string;
  resolution_note?: string;
  quiz?: {
    id: string;
    question: string;
    type: string;
    answer?: string | string[];
    knowledge_point?: string;
  };
  resolver?: {
    id: string;
    name: string;
  };
}

const reportTypeConfig = {
  display_error: {
    label: "显示错误",
    icon: "🖼️",
    color: "bg-red-100 text-red-700",
  },
  wrong_answer: {
    label: "答案错误",
    icon: "❌",
    color: "bg-orange-100 text-orange-700",
  },
  wrong_association: {
    label: "知识点错误",
    icon: "🔗",
    color: "bg-yellow-100 text-yellow-700",
  },
  duplicate: {
    label: "题目重复",
    icon: "📑",
    color: "bg-blue-100 text-blue-700",
  },
  unclear_wording: {
    label: "表述不清",
    icon: "💭",
    color: "bg-purple-100 text-purple-700",
  },
  other: { label: "其他问题", icon: "📝", color: "bg-gray-100 text-gray-700" },
};

const statusConfig = {
  pending: {
    label: "待处理",
    icon: Clock,
    color: "bg-yellow-100 text-yellow-700",
  },
  reviewing: {
    label: "处理中",
    icon: AlertCircle,
    color: "bg-blue-100 text-blue-700",
  },
  resolved: {
    label: "已解决",
    icon: CheckCircle,
    color: "bg-green-100 text-green-700",
  },
  dismissed: {
    label: "已忽略",
    icon: XCircle,
    color: "bg-gray-100 text-gray-700",
  },
};

export default function ReportManagement() {
  const [reports, setReports] = useState<QuizReport[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedReport, setSelectedReport] = useState<QuizReport | null>(null);
  const [statusFilter, setStatusFilter] = useState<QuizReport["status"][]>([
    "pending",
    "reviewing",
  ]);
  const [typeFilter, setTypeFilter] = useState<
    "all" | QuizReport["report_type"]
  >("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [resolutionNote, setResolutionNote] = useState("");
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [backendReady, setBackendReady] = useState(true);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingQuiz, setEditingQuiz] = useState<any>(null);
  const { success, error, warning, info, toasts, removeToast } = useToast();

  // Check user role
  const userData = authService.getCurrentUser();
  const isStudent = userData?.role === "student";

  useEffect(() => {
    fetchReports();
  }, [statusFilter, typeFilter]);

  const fetchReports = async () => {
    setLoading(true);
    try {
      const params: any = {
        limit: 50,
        offset: 0,
      };
      if (statusFilter.length > 0) params.status = statusFilter;
      if (typeFilter !== "all") params.report_type = typeFilter;

      const response = await api.reports.getManagementReports(params);

      if (response.success && response.data && response.data.data) {
        // The actual data is nested: response.data.data
        const actualData = response.data.data;

        // Transform the nested data structure to flat array of reports
        const transformedReports: QuizReport[] = [];

        actualData.forEach((quizData: any) => {
          // Each quizData contains a reports array
          if (quizData.reports && Array.isArray(quizData.reports)) {
            quizData.reports.forEach((report: any) => {
              const finalQuizId = report.quiz_id || quizData.quiz_id;
              transformedReports.push({
                id: report.id,
                quiz_id: finalQuizId,
                user_id: report.user_id,
                user_name: report.reporter?.name || "Unknown User",
                report_type: report.report_type,
                reason: report.reason,
                user_answer: report.user_answer,
                status: report.status,
                created_at: report.created_at,
                updated_at: report.updated_at,
                resolution_note: report.resolution_note,
                quiz: {
                  id: quizData.quiz_id,
                  question: quizData.question,
                  type: quizData.quiz_type,
                  knowledge_point: quizData.knowledge_point?.topic,
                },
                resolver: report.resolver,
              });
            });
          }
        });

        setReports(transformedReports);
      } else if (response.statusCode === 404) {
        // Backend endpoint not deployed yet - show message
        console.log("Report management endpoint not available yet");
        setBackendReady(false);
        setReports([]);
      } else {
        console.error("Failed to fetch reports:", response);
        console.log("Response status code:", response.statusCode);
        console.log("Response error:", response.error);
        setReports([]);
      }
    } catch (error) {
      console.error("Failed to fetch reports:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (
    reportId: string,
    newStatus: QuizReport["status"],
  ) => {
    try {
      const response = await api.reports.updateStatus(reportId, {
        status: newStatus,
        resolution_note: resolutionNote || undefined,
      });

      if (response.success) {
        // Update local state
        setReports((prev) =>
          prev.map((r) =>
            r.id === reportId
              ? { ...r, status: newStatus, resolution_note: resolutionNote }
              : r,
          ),
        );
        setShowDetailModal(false);
        setSelectedReport(null);
        setResolutionNote("");

        // Optionally refresh the list
        fetchReports();
      } else {
        console.error("Failed to update report status:", response);
      }
    } catch (error) {
      console.error("Failed to update report status:", error);
    }
  };

  const openDetailModal = (report: QuizReport) => {
    setSelectedReport(report);
    setResolutionNote(report.resolution_note || "");
    setShowDetailModal(true);
  };

  const handleEditQuiz = async (report: QuizReport | null) => {
    if (!report || !report.quiz_id) {
      error("无法获取题目ID");
      return;
    }

    try {
      // Fetch the full quiz details
      const response = await api.questions.getById(report.quiz_id);

      if (response.success && response.data && response.data.id) {
        setEditingQuiz(response.data);
        setShowEditModal(true);
        // Keep the detail modal open in the background
      } else {
        error(`加载题目详情失败: ${response.error || "数据格式错误"}`);
      }
    } catch (error) {
      console.error("Error loading quiz:", error);
      error("加载题目详情时发生错误");
    }
  };

  const handleSaveQuiz = (updatedQuiz: any) => {
    // Quiz saved successfully
    console.log("Quiz updated:", updatedQuiz);
    setShowEditModal(false);
    setEditingQuiz(null);

    // Optionally refresh the reports to show updated quiz content
    fetchReports();

    // Show success message
    success("题目已更新，您现在可以标记报告为已解决");
  };

  const handleDeleteQuiz = async (quizId: string) => {
    // Quiz deleted successfully
    console.log("Quiz deleted:", quizId);
    setShowEditModal(false);
    setEditingQuiz(null);

    // If the current report is open and it's for the deleted quiz, also close the detail modal
    if (selectedReport && selectedReport.quiz_id === quizId) {
      // Mark the report as resolved since the duplicate quiz was deleted
      await handleStatusChange(selectedReport.id, "resolved");
    }

    // Refresh the reports
    fetchReports();

    // Show success message
    success("题目已删除，相关报告已自动标记为已解决");
  };

  const filteredReports = reports.filter((report) => {
    if (
      searchTerm &&
      !report.quiz?.question.toLowerCase().includes(searchTerm.toLowerCase())
    ) {
      return false;
    }
    return true;
  });

  const pendingCount = reports.filter((r) => r.status === "pending").length;
  const reviewingCount = reports.filter((r) => r.status === "reviewing").length;

  return (
    <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">问题上报管理</h2>
        <p className="text-gray-600">查看和处理学生提交的题目问题上报</p>
      </div>

      <div>
          {/* Statistics */}
          <div className="grid grid-cols-4 gap-4 mb-6">
            <div className="bg-yellow-50 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-yellow-600">待处理</p>
                  <p className="text-2xl font-bold text-yellow-700">
                    {pendingCount}
                  </p>
                </div>
                <Clock className="w-8 h-8 text-yellow-500" />
              </div>
            </div>
            <div className="bg-blue-50 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-blue-600">处理中</p>
                  <p className="text-2xl font-bold text-blue-700">
                    {reviewingCount}
                  </p>
                </div>
                <AlertCircle className="w-8 h-8 text-blue-500" />
              </div>
            </div>
            <div className="bg-green-50 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-green-600">已解决</p>
                  <p className="text-2xl font-bold text-green-700">
                    {reports.filter((r) => r.status === "resolved").length}
                  </p>
                </div>
                <CheckCircle className="w-8 h-8 text-green-500" />
              </div>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">总报告</p>
                  <p className="text-2xl font-bold text-gray-700">
                    {reports.length}
                  </p>
                </div>
                <Flag className="w-8 h-8 text-gray-500" />
              </div>
            </div>
          </div>

          {/* Filters */}
          <div className="flex flex-wrap gap-4 mb-6">
            <div className="flex-1 min-w-[300px]">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="搜索题目内容..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
            </div>

            <div className="relative">
              <button
                className="px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 bg-white flex items-center gap-2 min-w-[180px]"
                onClick={() => {
                  const dropdown = document.getElementById('status-dropdown');
                  dropdown?.classList.toggle('hidden');
                }}
              >
                <Filter className="w-4 h-4" />
                <span>
                  {statusFilter.length === 0
                    ? '所有状态'
                    : statusFilter.length === 4
                    ? '所有状态'
                    : `已选 ${statusFilter.length} 个`}
                </span>
              </button>
              <div
                id="status-dropdown"
                className="hidden absolute top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-10 p-2 min-w-[180px]"
              >
                {[
                  { value: 'pending' as const, label: '待处理' },
                  { value: 'reviewing' as const, label: '处理中' },
                  { value: 'resolved' as const, label: '已解决' },
                  { value: 'dismissed' as const, label: '已忽略' },
                ].map((status) => (
                  <label
                    key={status.value}
                    className="flex items-center gap-2 px-3 py-2 hover:bg-gray-50 rounded cursor-pointer"
                  >
                    <input
                      type="checkbox"
                      checked={statusFilter.includes(status.value)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setStatusFilter([...statusFilter, status.value]);
                        } else {
                          setStatusFilter(
                            statusFilter.filter((s) => s !== status.value)
                          );
                        }
                      }}
                      className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                    />
                    <span className="text-sm">{status.label}</span>
                  </label>
                ))}
                <div className="border-t mt-2 pt-2 flex gap-2">
                  <button
                    onClick={() =>
                      setStatusFilter([
                        'pending',
                        'reviewing',
                        'resolved',
                        'dismissed',
                      ])
                    }
                    className="flex-1 text-xs px-2 py-1 text-blue-600 hover:bg-blue-50 rounded"
                  >
                    全选
                  </button>
                  <button
                    onClick={() => setStatusFilter([])}
                    className="flex-1 text-xs px-2 py-1 text-gray-600 hover:bg-gray-50 rounded"
                  >
                    清空
                  </button>
                </div>
              </div>
            </div>

            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value as any)}
              className="px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">所有类型</option>
              <option value="display_error">显示错误</option>
              <option value="wrong_answer">答案错误</option>
              <option value="wrong_association">知识点错误</option>
              <option value="duplicate">题目重复</option>
              <option value="unclear_wording">表述不清</option>
              <option value="other">其他问题</option>
            </select>
          </div>

          {/* Reports List */}
          {loading ? (
            <div className="text-center py-12">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <p className="mt-2 text-gray-600">加载中...</p>
            </div>
          ) : !backendReady ? (
            <div className="text-center py-12">
              <AlertCircle className="w-12 h-12 text-yellow-500 mx-auto mb-3" />
              <p className="text-gray-700 font-medium">报告功能正在部署中</p>
              <p className="text-gray-500 text-sm mt-2">
                此功能即将上线，请稍后再试
              </p>
            </div>
          ) : filteredReports.length === 0 ? (
            <div className="text-center py-12">
              <Flag className="w-12 h-12 text-gray-300 mx-auto mb-3" />
              <p className="text-gray-500">暂无报告</p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredReports.map((report) => {
                const StatusIcon = statusConfig[report.status].icon;
                const typeConfig = reportTypeConfig[report.report_type];

                return (
                  <div
                    key={report.id}
                    className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <span className="px-2 py-1 bg-gray-200 text-gray-600 rounded text-xs font-mono">
                            题目ID: {report.quiz_id}
                          </span>
                          <span
                            className={`px-2 py-1 rounded text-xs font-medium ${typeConfig.color}`}
                          >
                            {typeConfig.icon} {typeConfig.label}
                          </span>
                          <span
                            className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${statusConfig[report.status].color}`}
                          >
                            <StatusIcon className="w-3 h-3 mr-1" />
                            {statusConfig[report.status].label}
                          </span>
                          <span className="text-xs text-gray-500 flex items-center">
                            <User className="w-3 h-3 mr-1" />
                            {report.user_name || "未知用户"}
                          </span>
                          <span className="text-xs text-gray-500 flex items-center">
                            <Calendar className="w-3 h-3 mr-1" />
                            {new Date(report.created_at).toLocaleDateString()}
                          </span>
                        </div>

                        <div className="text-sm text-gray-900 mb-2 line-clamp-2">
                          <span className="font-medium">题目：</span>
                          {report.quiz?.question}
                        </div>

                        {report.reason && (
                          <div className="text-sm text-gray-600 mb-2">
                            <span className="font-medium">问题描述：</span>
                            {report.reason}
                          </div>
                        )}

                        {report.quiz?.knowledge_point && (
                          <div className="text-xs text-gray-500">
                            <span className="font-medium">知识点：</span>
                            {report.quiz.knowledge_point}
                          </div>
                        )}
                      </div>

                      <button
                        onClick={() => openDetailModal(report)}
                        className="ml-4 px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors flex items-center"
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        处理
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* Detail Modal */}
          {showDetailModal && selectedReport && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
              <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[80vh] overflow-y-auto">
                <div className="p-6">
                  <h3 className="text-xl font-bold text-gray-900 mb-4">
                    处理问题上报
                  </h3>

                  <div className="space-y-4">
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="block text-sm font-medium text-gray-700">
                          题目
                        </label>
                        <span className="text-xs text-gray-500 font-mono bg-gray-100 px-2 py-1 rounded">
                          ID: {selectedReport.quiz_id || "未知"}
                        </span>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg text-sm">
                        {selectedReport.quiz?.question}
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        问题类型
                      </label>
                      <span
                        className={`inline-flex items-center px-3 py-1 rounded-lg text-sm font-medium ${reportTypeConfig[selectedReport.report_type].color}`}
                      >
                        {reportTypeConfig[selectedReport.report_type].icon}{" "}
                        {reportTypeConfig[selectedReport.report_type].label}
                      </span>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        问题描述
                      </label>
                      <div className="p-3 bg-gray-50 rounded-lg text-sm">
                        {selectedReport.reason || "无描述"}
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        学生信息
                      </label>
                      <div className="text-sm text-gray-600">
                        {selectedReport.user_name || "未知用户"} -{" "}
                        {new Date(selectedReport.created_at).toLocaleString()}
                      </div>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        处理备注
                      </label>
                      <textarea
                        value={resolutionNote}
                        onChange={(e) => setResolutionNote(e.target.value)}
                        placeholder="输入处理备注..."
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        rows={3}
                      />
                    </div>

                    <div className="flex justify-between pt-4 border-t">
                      <button
                        onClick={() => handleEditQuiz(selectedReport)}
                        className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center"
                      >
                        <Edit className="w-4 h-4 mr-2" />
                        编辑题目
                      </button>

                      <div className="flex gap-3">
                        <button
                          onClick={() => setShowDetailModal(false)}
                          className="px-4 py-2 text-gray-700 hover:text-gray-900 transition-colors"
                        >
                          取消
                        </button>
                        <button
                          onClick={() =>
                            handleStatusChange(selectedReport.id, "dismissed")
                          }
                          className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                        >
                          忽略
                        </button>
                        <button
                          onClick={() =>
                            handleStatusChange(selectedReport.id, "reviewing")
                          }
                          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                        >
                          标记处理中
                        </button>
                        <button
                          onClick={() =>
                            handleStatusChange(selectedReport.id, "resolved")
                          }
                          className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                        >
                          标记已解决
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

      {/* Quiz Edit Modal */}
      <QuizEditModal
        quiz={editingQuiz}
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false);
          setEditingQuiz(null);
        }}
        onSave={handleSaveQuiz}
        onDelete={handleDeleteQuiz}
      />

      {/* Toast Notifications */}
      <ToastContainer toasts={toasts} onRemove={removeToast} />
    </div>
  );
}
